﻿using LeakView.common;
using LeakView.database;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeakView.service
{
    class NetworkStateManager : Splashable
    {

        private static readonly ILog log = LogManager.GetLogger(typeof(NetworkStateManager));


        public static readonly NetworkStateManager me = new NetworkStateManager();

        private bool head = false;
        private bool tail = false;

        AjaxLeakPair pair = null;

        void Splashable.splash(bool flag)
        {
            this.dispatch();
        }

        public void dispatch()
        {

            if(MainModule.pair.Value.Valid)
            {
                pair = MainModule.pair.Value.Value;
            }

            var status = MainModule.status.Value;

            if (pair == null || status == null || !status.Valid)
            {
                return;
            }

            var pair_status = status.Value;

            if(pair_status.head != head)
            {

                log.Info("Head network status change to " + pair_status.head);

                head = pair_status.head;

                Entities.AddNetowrkAlarm(pair.head.id, pair.head.name, pair_status.head);
                
            }

            if(pair_status.tail != tail)
            {
                log.Info("Tail network status change to " + pair_status.tail);

                tail = pair_status.tail;

                Entities.AddNetowrkAlarm(pair.tail.id, pair.tail.name, pair_status.tail);
                
            }

        }
    }
}
